<?php

namespace App\Http\Controllers\AliPay;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\Utils\Guard;
use App\Http\Controllers\ApiController;
use App\Exceptions\ApiErrCode;
use Illuminate\Support\Carbon;
use Yansongda\Pay\Contracts\GatewayApplicationInterface;
use Yansongda\LaravelPay\PayServiceProvider;
use Illuminate\Support\Facades\DB;
use Yansongda\LaravelPay\Facades\Pay;
use App\Models\Order;
use App\Models\Charge;
use Illuminate\Support\Facades\Log;
use Yansongda\Pay\Log as YanLog;
// use Illuminate\Support\Facades\Cache;
// use SimpleSoftwareIO\QrCode\Facades\QrCode;

class AliPayController extends ApiController
{
    public function alipay(Request $request)
    {
        $user = Guard::customer();
        if (! $user) {
            $code = ApiErrCode::JWT_TOKEN_INVALID;
            $error = trans('middleware.token_invalid');
            return $this->response(compact('code','error'));
        }
        $out_trade_no = date('YmdHis').substr(microtime(), 2, 5).mt_rand(10,99);
        $total_amount = floatval($request->amount);
        $subject = $request->subject;
        
        $orders = new Order;
        $orders->customer_id = $user['id'];
        $orders->order_no = $out_trade_no;
        $orders->amount = $total_amount*100;
        $orders->subject = $subject;
        $orders->created_at = Carbon::now();
        if ($orders->save()) {
            $order = [
                'out_trade_no' => $out_trade_no,
                'total_amount' => $total_amount,
                'subject' => $subject,
            ];
            return Pay::alipay()->web($order);
        }
        // if(empty($alipay->code) || $alipay->code !== '10000') return false;
        // return  QrCode::encoding('UTF-8')->size(300)->generate($alipay->qr_code);
    }

    public function return()
    {
        $data = Pay::alipay()->verify(); // 是的，验签就这么简单！
        return redirect()->away('https://facecloud.panxsoft.com/web-admin/#/home');
        // 订单号：$data->out_trade_no
        // 支付宝交易号：$data->trade_no
        // 订单总金额：$data->total_amount
    }

    public function notify()
    {
        $alipay = Pay::alipay();
    
        try{
            $data = $alipay->verify(); // 是的，验签就这么简单！
            if ($data->trade_status == 'TRADE_SUCCESS' || $data->trade_status == 'TRADE_FINISHED'){
                $order = Order::where('order_no', $data->out_trade_no)->first();
                if (!isset($order)) {
                    return;
                }
                if (($data->total_amount)*100 != $order->amount) {
                    return;
                }
                if ($data->app_id != env('ALI_APP_ID')) {
                    return;
                }
                Order::where('order_no', $data->out_trade_no)
                    ->update(['success' => 1]);

                $charges = Charge::where('customer_id', $order->customer_id)->latest()->value('change_after');
                $amount = empty($charges) ? 0 : $charges;
                $change_after = intval($amount + ($data->total_amount)*100);

//                $change_type = '支付宝充值' . $data->total_amount . '元';
                $change_type = 'charge';
                $params = array(
                    'out_trade_no' => $data->out_trade_no,
                    'total_amount' => $data->total_amount,
                    'trade_status' => $data->trade_status,
                    'trade_no'     => $data->trade_no,
                    'notify_id'    => $data->notify_id,
                    'app_id'       => $data->app_id,
                    'buyer_id'     => $data->buyer_id,
                    'seller_id'    => $data->seller_id,
                    'subject'      => $data->subject,
                    'gmt_create'   => $data->gmt_create,
                    'notify_time'  => $data->notify_time,
                );
                $charge = new Charge;
                $charge->customer_id = $order->customer_id;
                $charge->change_before = $amount;
                $charge->change_after = $change_after;
                $charge->change_type = $change_type;
                $charge->change_params = json_encode($params);
                $charge->remark = $order->subject;
                $charge->created_at = Carbon::now();
                $charge->save();
            }

            // 请自行对 trade_status 进行判断及其它逻辑进行判断，在支付宝的业务通知中，只有交易通知状态为 TRADE_SUCCESS 或 TRADE_FINISHED 时，支付宝才会认定为买家付款成功。
            // 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号；
            // 2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额）；
            // 3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）；
            // 4、验证app_id是否为该商户本身。
            // 5、其它业务逻辑情况

            YanLog::debug('Alipay notify', $data->all());
        } catch (\Exception $e) {
            // $e->getMessage();
        }

        return $alipay->success();// laravel 框架中请直接 `return $alipay->success()`
    }
}
